package com.zh.config.fragment

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.SizeUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.luck.picture.lib.entity.LocalMedia
import com.zh.common.R
import com.zh.common.base.BaseFragment
import com.zh.common.databinding.FragmentPictureBinding
import com.zh.common.databinding.ItemZhPictureBinding
import com.zh.common.ktx.viewBinding
import com.zh.common.picture.ImageFileCropEngine
import com.zh.common.picture.PictureSelectorUtils
import com.zh.common.utils.GlideManager
import com.zh.common.view.dialog.BottomDialog
import java.util.*
import kotlin.collections.ArrayList

/**
 * 公用图片选择
 */
class PictureFragment : BaseFragment<FragmentPictureBinding>() {

    private var isShowAdd = true //是否显示添加图片按钮
    private val margin = SizeUtils.dp2px(5f)
    private var selectList = ArrayList<LocalMedia>()
    private val mAdapter by lazy { PictureAdapter() }

    var deleteImg = R.mipmap.delete_black//删除按钮
    var takeImg = R.mipmap.iv_take_photo//选择图片按钮
    var needShowTake = true//是否需要显示选择图片按钮
    var maxSelectNum = 9 //最大选择数量,默认9张
    val cropEngine: ImageFileCropEngine? = null

    /**
     * 获取选择的图片
     */
    fun getPictureList(): MutableList<LocalMedia> = selectList

    override fun initView(savedInstanceState: Bundle?) {
        //TODO 两边距离 总10
        mItemHelper.attachToRecyclerView(viewBinding.recyclerView)
        viewBinding.recyclerView.setPadding(margin, margin, 0, margin)
        viewBinding.recyclerView.adapter = mAdapter
        mAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun onItemClick(adapter: RecyclerView.Adapter<*>, view: View, position: Int) {
                if (isShowAdd && position == selectList.size) {
                    openPicture(context)
                } else {
                    previewPicture(position)
                }
            }
        })
    }

    /**
     * 选择相册弹框
     */
    fun showSelectDialog() {
        activity?.let {
            BottomDialog.Builder(it)
                .setContentList(arrayOf("相机", "相册"))
                .setPositivePositionItem { _, which ->
                    when (which) {
                        0 -> openCamera(it)
                        1 -> openPicture(it)
                    }
                }.create().show()
        }
    }

    private fun openPicture(context: Context?) {
        context?.let {
            PictureSelectorUtils.openGallery(
                it, selectList, maxSelectNum, cropEngine
            ) { b, list ->
                selectList = list
                mAdapter.notifyDataSetChanged()
            }
        }
    }

    private fun openCamera(context: Context?) {
        context?.let {
            PictureSelectorUtils.openCamera(
                it, PictureSelectorUtils.circleCropEngine(true)
            ) { b, list ->
                selectList = list
                mAdapter.notifyDataSetChanged()
            }
        }
    }

    /**
     * 预览图片
     */
    private fun previewPicture(position: Int) {
        context?.let {
            PictureSelectorUtils.openPreview(it, position, selectList)
        }
    }

    interface OnItemClickListener {
        fun onItemClick(adapter: RecyclerView.Adapter<*>, view: View, position: Int)
    }

    inner class PictureAdapter : RecyclerView.Adapter<BaseViewHolder>() {

        //TODO 显示4张图片
        private var width = (ScreenUtils.getScreenWidth() - margin * 4) / 4
        private var mOnItemClickListener: OnItemClickListener? = null

        fun setOnItemClickListener(listener: OnItemClickListener?) {
            this.mOnItemClickListener = listener
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
            return BaseViewHolder(parent.viewBinding<ItemZhPictureBinding>().root)
        }

        override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
            //显示图片
            val ivImage: ImageView = holder.getView(R.id.ivImage)
            val lp = ivImage.layoutParams as FrameLayout.LayoutParams
            lp.rightMargin = margin
            lp.bottomMargin = margin
            lp.width = width
            lp.height = width
            ivImage.layoutParams = lp
            if (selectList.size != holder.layoutPosition) {
                GlideManager.loadUrl(selectList[holder.layoutPosition].compressPath, ivImage)
            }

            //点击删除
            val ivDelete: ImageView = holder.getView(R.id.ivDelete)
            ivDelete.setImageResource(deleteImg)
            ivDelete.setOnClickListener {
                selectList.removeAt(holder.layoutPosition)
                notifyItemRemoved(holder.layoutPosition)
            }

            //控制显示添加图片按钮
            if (isShowAdd && selectList.size == holder.layoutPosition) {
                ivDelete.visibility = View.GONE
                ivImage.scaleType = ImageView.ScaleType.FIT_XY
                ivImage.setImageResource(takeImg)
            } else {
                ivDelete.visibility = View.VISIBLE
            }

            //长按拖拽
            holder.itemView.setOnLongClickListener {
                if (selectList.size > holder.layoutPosition) {
                    mItemHelper.startDrag(holder)
                }
                false
            }

            //点击事件
            holder.itemView.setOnClickListener {
                mOnItemClickListener?.onItemClick(
                    this@PictureAdapter,
                    holder.itemView,
                    holder.layoutPosition
                )
            }
        }

        override fun getItemCount(): Int {
            var mCount = 0
            if (needShowTake && selectList.size < maxSelectNum) {
                isShowAdd = true
                mCount = selectList.size + 1
            } else {
                isShowAdd = false
                mCount = selectList.size
            }
            return mCount
        }
    }

    var mItemHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {

        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ): Int {
            return if (recyclerView.layoutManager is GridLayoutManager) {
                val dragFlags: Int = ItemTouchHelper.UP or ItemTouchHelper.DOWN or
                        ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                val swipeFlags = 0
                makeMovementFlags(dragFlags, swipeFlags)
            } else {
                val dragFlags: Int = ItemTouchHelper.UP or ItemTouchHelper.DOWN
                val swipeFlags = 0
                makeMovementFlags(dragFlags, swipeFlags)
            }
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            //得到当拖拽的viewHolder的Position
            val fromPosition: Int = viewHolder.adapterPosition
            //拿到当前拖拽到的item的viewHolder
            val toPosition: Int = target.adapterPosition
            if (toPosition >= selectList.size) return false
            if (fromPosition < toPosition) {
                for (i in fromPosition until toPosition) {
                    Collections.swap(selectList, i, i + 1)
                }
            } else {
                for (i in fromPosition downTo toPosition + 1) {
                    Collections.swap(selectList, i, i - 1)
                }
            }
            mAdapter.notifyItemMoved(fromPosition, toPosition)
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
            Log.e("tag", "拖拽完成 方向$direction")
        }

        override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
            super.onSelectedChanged(viewHolder, actionState)
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) viewHolder?.itemView?.setBackgroundColor(
                Color.LTGRAY
            )
        }

        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)
            viewHolder.itemView.setBackgroundColor(0)
        }

        //重写拖拽不可用
        override fun isLongPressDragEnabled(): Boolean {
            return false
        }
    })
}